import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { uniqueId, remove, forEach, assign } from 'lodash';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { MenuItem, OptionItem } from '@iux/live';

interface DemoUser {
  id: string;
  name: string;
  age: number;
  expand: boolean;
  random: number;
  disabled: boolean;
  isEditing?: boolean;
}

@Component({
  selector: 'app-operation',
  templateUrl: './operation.component.html',
  styles: [
    `
      .table-section > h3 {
        margin: 16px 0 8px 0;
      }
      .table-section lv-datatable {
        margin-bottom: 16px;
      }
      .edit-form lv-form-control > .lv-input {
        width: 300px;
      }
      .lv-input {
        width: 100%;
      }
    `,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class OperationComponent implements OnInit {
  data: DemoUser[];
  cacheDataMap: { [key: string]: DemoUser };
  formGroupMap: { [key: string]: FormGroup } = {};
  contactOptions: OptionItem[];
  actionItems: MenuItem[];

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.initData();
  }

  initData() {
    this.data = Array.from({ length: 4 }).map((item, key) => {
      return this.initUser(key);
    });
    this.setCacheDataMap();
    this.contactOptions = this.initOptions();
  }

  setCacheDataMap() {
    this.cacheDataMap = {};
    forEach(this.data, item => (this.cacheDataMap[item.id] = { ...item })); // item内部属性存在复杂类型需要cloneDeep深拷贝
  }

  updateCacheDataMap(source: DemoUser) {
    this.cacheDataMap[source.id] = { ...source };
  }

  initUser(key: number) {
    return {
      id: uniqueId('uid'),
      name: `user${key}`,
      age: 10 + key,
      expand: false,
      random: parseInt(`${Math.random() * 100}`, 10),
      disabled: Math.random() > 0.5,
      isEditing: false, // 自定义控制是否为编辑状态字段
    };
  }

  initOptions() {
    return [
      {
        label: 'email',
        isLeaf: true,
      },
      {
        label: 'phone',
        isLeaf: true,
      },
    ];
  }

  editRow(source: DemoUser) {
    source.isEditing = true;
    this.initForm(source);
  }

  deleteRow(source: DemoUser) {
    remove(this.data, item => item.id === source.id);
    this.data = [...this.data];
  }

  saveRow(source: DemoUser) {
    assign(source, this.cacheDataMap[source.id]);
    source.isEditing = false;
  }

  cancelRow(source: DemoUser) {
    this.updateCacheDataMap(source);
    source.isEditing = false;
  }

  initForm(source) {
    this.formGroupMap[source.id] = this.fb.group({
      name: [source.name, Validators.required],
      password: [source.password, Validators.required],
      contact: [source.contact || 'email', Validators.required],
    });
  }

  saveComplexRow(source: DemoUser) {
    assign(source, this.formGroupMap[source.id].value);
    source.isEditing = false;
  }

  itemCallback: (data) => Array<MenuItem> = data => {
    this.actionItems = [
      {
        id: 'Edit',
        label: 'Edit',
        onClick: () => {
          this.editRow(data);
        },
      },
      {
        id: 'Delete',
        label: 'Delete',
        onClick: () => {
          this.deleteRow(data);
        },
      },
    ];

    return this.actionItems;
  };
}
